﻿using System;
using System.Collections.Generic;
using System.Linq;

using System.Xml.Linq;
using System.Text;

using Microsoft.Office.Tools.Word;
using VSTO = Microsoft.Office.Tools.Word;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools.Word.Extensions;

using LocalView;

namespace ContentProcessor
{
    public class ProcessText
    {
         public string DoAction(ILocalView localView)
        {
            //Send query by post
            System.Net.WebClient wc = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
            nvc.Add("appid", Properties.Settings.Default.AppId);
            nvc.Add("context", localView.GetContentText());
            XDocument xdoc = XDocument.Parse(Encoding.UTF8.GetString(wc.UploadValues("http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction", "POST", nvc)));
            //Iterate through keywords
            VSTO.SmartTag tag = new OCISmartTag("http://www.upriseapps.com/#officeincloud", "Office In Cloud", null, null);
            VSTO.Action myAction = new VSTO.Action("Open in Web");
            tag.Actions = new VSTO.Action[] { myAction };

            myAction.Click += new VSTO.ActionClickEventHandler(myAction_Click);

            StringBuilder keywords = new StringBuilder();
            foreach (var xresult in xdoc.Elements().First().Elements())
            {
                keywords.AppendLine(xresult.Value);
                tag.Terms.Add(xresult.Value);
                tag.Expressions.Add(new System.Text.RegularExpressions.Regex("[ ]" + xresult.Value + "[ |.]"));

                string str = xresult.Value;
                string[] strs = str.Split(new char[] { ' ' });

                foreach (string s in strs)
                    localView.HighlightSmartTags(s);
            }

            tag.Terms.Add("Microsoft");
            tag.Terms.Add("Office");
            tag.Expressions.Add(new System.Text.RegularExpressions.Regex("[A|a]ndriy\\s[K|k]andzyuba"));
            //Show a message box!
            //System.Windows.Forms.MessageBox.Show(keywords.ToString(), "Keywords");

            //KeywordsBox.Text = keywords.ToString();
            localView.SmartTagActions(tag);

            return keywords.ToString();
        }

        public void myAction_Click(object sender, VSTO.ActionEventArgs e)
        {
            e.Range.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdYellow;
            System.Windows.Forms.MessageBox.Show(String.Format("Open in LinkedIn", e.Range));
        }
    }
}
